package cn.netctoss.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.netctoss.entity.Admin;
import cn.netctoss.entity.Cost;
import cn.netctoss.service.ApplicationsException;
import cn.netctoss.service.FindCostService;
import cn.netctoss.service.LoginService;
import cn.netctoss.util.ImageUtil;


@Controller
public class MainController {

	@Resource(name="loginService")
	private LoginService loginService;
	
	@Resource(name="findAllCost")
	private FindCostService findCost;
	
	
	@RequestMapping("/findCost.do")
	public String fingCost(HttpServletRequest req,HttpSession session){
		
		List<Cost> list = findCost.findAllCost();
		
		session.setAttribute("costs", list);
		
		System.out.println(list);
		
		return  "find";
		
	}
	
	
	
	
	@RequestMapping("/toLogin.do")
	public String toLogin(){
		return "login";
	}
	
	@RequestMapping("/checkcode.do")
	public void checkcode(HttpServletResponse res ) throws IOException{
		BufferedImage image=(BufferedImage)ImageUtil.createImage()[1];
		
		OutputStream os = res.getOutputStream();
		javax.imageio.ImageIO.write(image, "jpeg",os);
		os.close();
		
		
	}
		
	
	
	
	@RequestMapping("/login.do")
	public String toIndex(HttpServletRequest req,HttpSession session){
		//读取账号,密码
		String adminCode = req.getParameter("adminCode");
		System.out.println(adminCode);
		String pwd = req.getParameter("pwd");
		System.out.println(pwd);
		//调用业务层提供的服务
		
			Admin admin = loginService.checkLogin(adminCode, pwd);
			session.setAttribute("admin",admin);
		
			return "redirect:toIndex.do";
		
	}
	
	
	@RequestMapping("/toIndex.do")
	public String index(){
		return "index";
	}
	
	
	@ExceptionHandler
	public String handleEX(Exception e,HttpServletRequest req){
		if(e instanceof ApplicationsException){
			
			req.setAttribute("login_failed",e.getMessage());
			return "login";
			
		}
		return "error";
		
	}
	
	
	
	

}














